import React, { Component } from 'react';
import {
  View,
  Text,
  TextInput,
  Button,
  StyleSheet,
  ScrollView,
  Image,
  TouchableOpacity,
  ImageBackground,
  ToastAndroid,
  DeviceEventEmitter,
} from 'react-native';
import * as ImagePicker from 'react-native-image-picker';
import Icon from 'react-native-vector-icons/AntDesign';
import Loading from '../../compenent/Loading';
import { DOMAIN_URL, addEvent, eventUpdate, uploadFile } from '../../../util/api';
import { DateTimePickerAndroid } from '@react-native-community/datetimepicker';
import moment, { months } from 'moment';
import { PAGENAME } from '../../../util/PageName';
import { style } from '../../../theme';
import { FILE_TYPE } from '../../../util/global';
 import DeleteIcon from '../../compenent/DeleteIcon';

class ActiveEditScreen extends Component {
  constructor(props) {
    super(props);
    console.log(props.route.params);
    console.log(props.route.params?.data);
    this.state = {
      data: props.route.params?.data,
      name: props.route.params?.data.name || '',
      description: props.route.params?.data.description || '',
      score: `${props.route.params?.data.score || 2}`,
      images: props.route.params?.data.imageDetails || [],
      // preImages: props.route.params?.data.imageDetails || [],
      endTime: moment(props.route.params?.data.endTime).toDate() || new Date(),
      // 'descriptiondescriptiondescriptiondescriptiondescriptiondescriptiondescriptiondescriptiondescriptiondescription',
      // score: '2',
      // images: [],
      // endTime: new Date(),
      loading: false,
    };
  }

  pickImage = () => {
    ImagePicker.launchImageLibrary(
      { mediaType: 'photo', selectionLimit: 5 },
      response => {
        if (!response.didCancel) {
          this.setState(prevState => ({
            images: [
              ...new Set([
                ...prevState.images,
                ...(response.assets.map(asset => asset) || []),
              ]),
            ],
          }));
        }
      },
    );
  };
  submitData = async () => {
    this.setState({ loading: true });
    let imgs = []
    // let imgs: any[] = this.state.preImages.map(v => v.id);
    console.log(this.state.images);
    for (let index = 0; index < this.state.images.length; index++) {
      const element = this.state.images[index];
      if(element.id){
        imgs.push(element.id);
        continue
      }
      await uploadFile(
        {
          uri: element.uri, // 替换为实际文件路径
          type: element.type,
          name: element.fileName,
        },
        FILE_TYPE.IMAGE,
      )
        .then(res => {
          console.log(res);
          if (res.code == 0) {
            console.log(`${element} upload success.`);
            imgs.push(res.data.id);
          } else {
            ToastAndroid.show(`上传失败:${res.msg}`, 2000);
          }
        })
        .catch(e => {
          console.log(e);
          ToastAndroid.show(`上传失败:${e}`, 2000);
        });
    }
    // this.setState({loading: false});
    if (imgs.length > 0) {
      if (this.state.data?.id) {
        // 编辑
        const { data } = this.state
        data.name = this.state.name
        data.description = this.state.description
        data.endTime = moment(this.state.endTime).format('YYYY-MM-DD HH:MM:SS')
        data.image = imgs
        data.score = Number.parseInt(this.state.score, 10)

        eventUpdate(data).then(res => {
          console.log('update event', res);
          if (res.code == 0) {
            ToastAndroid.show('更新成功！', 3000);
            this.props.navigation.goBack({ refresh: true });
          } else {
            ToastAndroid.show(`更新失败:${res.msg}`, 3000);
            this.props.navigation.goBack({ refresh: true });
          }
          return;
        }).catch(e => {
          this.props.navigation.goBack({ refresh: true });
          // DeviceEventEmitter.emit(PAGENAME.ACTIVE_DETAIL, { name: 'back' });

        })
          .finally(() => {
            this.setState({ loading: false });
          });
      } else {
        // 更新
        addEvent({
          name: this.state.name,
          description: this.state.description,
          endTime: moment(this.state.endTime).format('YYYY-MM-DD HH:MM:SS'),
          image: imgs,
          score: Number.parseInt(this.state.score, 10),
        })
          .then(res => {
            console.log('add event', res);
            if (res.code == 0) {
              ToastAndroid.show('添加成功！', 3000);
              this.props.navigation.goBack({ refresh: true });
            } else {
              ToastAndroid.show(`添加失败:${res.msg}`, 3000);
            }
            return;
          })
          .finally(() => {
            this.setState({ loading: false });
          });
      }


    } else {
      this.setState({ loading: false });
    }
  };
  inputEndTime = (event, value) => {
    this.setState({ endTime: value });
  };

  render() {
    const { name, description, score, images, preImages, endTime } = this.state;
    return (
      // <ImageBackground
      //   source={require('../../../assets/images/bg.jpg')} // 替换为您自己的背景图路径
      //   style={{flex: 1}}
      //   imageStyle={{opacity: 0.4}} // 修改透明度，范围为0（完全透明）到1（完全不透明）
      // >
      <View>
        <Loading loading={this.state.loading} />
        <ScrollView contentContainerStyle={styles.container}>
          <Text style={style.subTitle}>标题</Text>
          <TextInput
            style={style.inputArea}
            value={name}
            onChangeText={text => this.setState({ name: text })}
          />
          <Text style={style.subTitle}>分数</Text>
          <TextInput
            style={style.inputArea}
            value={score}
            onChangeText={text => this.setState({ score: text })}
          />
          <Text style={style.subTitle}>结束时间</Text>
          <TouchableOpacity
            onPress={() => {
              DateTimePickerAndroid.open({
                value: endTime,
                onChange: this.inputEndTime,
                mode: 'date',
                is24Hour: true,
              });
            }}>
            <TextInput
              editable={false}
              style={style.inputArea}
              value={`${moment(endTime).format('YYYY-MM-DD')}`}
            />
          </TouchableOpacity>
          <Text style={style.subTitle}>描述内容</Text>
          <TextInput
            style={[style.inputArea, { height: 100 }]}
            value={description}
            onChangeText={text => this.setState({ description: text })}
            multiline
          />
          <View style={{ flexDirection: 'row' }}>
            <Text style={style.subTitle}>图片</Text>
          </View>
          <View style={{ flexDirection: 'row', flexWrap: 'wrap' }}>
            {/*{preImages.map((image, index) => (*/}
            {/*  <View key={index} style={{ position: 'relative', margin: 4 }}>*/}
            {/*    <Image source={{ uri: `${DOMAIN_URL}${image.path}` }} style={styles.image} />*/}
            {/*    <TouchableOpacity*/}
            {/*      style={{*/}
            {/*        position: 'absolute',*/}
            {/*        top: 2,*/}
            {/*        right: 2,*/}
            {/*        backgroundColor: 'rgba(0, 0, 0, 0.5)',*/}
            {/*        width: 30,*/}
            {/*        height: 30,*/}
            {/*        justifyContent: 'center',*/}
            {/*        alignItems: 'center',*/}
            {/*      }}*/}
            {/*      onPress={() => {*/}
            {/*        const updatedImages = images.filter(*/}
            {/*          (value, idx) => idx !== index,*/}
            {/*        );*/}
            {/*        this.setState({ images: updatedImages });*/}
            {/*      }}>*/}
            {/*      <DeleteIcon />*/}
            {/*    </TouchableOpacity>*/}
            {/*  </View>*/}
            {/*))}*/}
            {images.map((image, index) => (
              <View key={index} style={{ position: 'relative', margin: 4 }}>
                <Image source={{ uri: image.uri||`${DOMAIN_URL}${image.path}` }} style={styles.image} />
                <TouchableOpacity
                  style={{
                    position: 'absolute',
                    top: 2,
                    right: 2,
                    backgroundColor: 'rgba(0, 0, 0, 0.5)',
                    width: 30,
                    height: 30,
                    justifyContent: 'center',
                    alignItems: 'center',
                  }}
                  onPress={() => {
                    const updatedImages = images.filter(
                      (value, idx) => idx !== index,
                    );
                    this.setState({ images: updatedImages });
                  }}>
                  <DeleteIcon />
                </TouchableOpacity>
              </View>
            ))}
            <TouchableOpacity
              style={{
                width: 75,
                height: 75,
                alignItems: 'center',
                justifyContent: 'center',
                borderWidth: 1,
                borderColor: 'gray',
                position: 'relative',
                margin: 4,
              }}
              onPress={() => {
                this.pickImage();
              }}>
              <Icon
                name={'plus'}
                size={50}
                color={'rgba(0, 0, 0, 0.3)'}
                style={{ width: 50, height: 50 }}
              />
            </TouchableOpacity>
          </View>
          <View style={{ flexDirection: 'row', alignSelf: 'center', marginVertical: 15 }}>
            <View
              style={style.pageButton}>
              <Button title="提交" onPress={() => this.submitData()} />
            </View>
          </View>
        </ScrollView>
        {/* </ImageBackground> */}
      </View>

    );
  }
}

const styles = StyleSheet.create({
  container: {
    padding: 20,
  },
  label: {
    fontSize: 16,
    marginBottom: 5,
    fontWeight: 'bold',
  },

  button: {
    fontSize: 16,
    color: 'blue',
    marginBottom: 10,
  },
  image: {
    width: 75,
    height: 75,
    marginBottom: 10,
  },
});

export default ActiveEditScreen;
